/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: key_value_storage.cpp
 *
 * Purpose: key value storage(persistency) implementation for base library
 *
 * Developer:
 *   wen.gu , 2019-10-16
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#include "panda/per/key_value_storage.h"
#include "panda/core/json.h"
#include "panda/per/file_storage.h"

#define LOG_TAG "kvst"
#include "panda/core/log.h"

namespace panda
{
namespace per
{
/******************************************************************************
 **    MACROS
 ******************************************************************************/
#define KVS_FS_NAME ".kvstore"
/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/



/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/

class KeyValueStorage::impl
{
public:
    panda::core::Value mKvs;
    std::string mName = "";
    std::shared_ptr<FileStorage> mFs = nullptr;
    std::unique_ptr<FileAccessor> mAccessor = nullptr;
public:
    bool parseKVS();

};

bool KeyValueStorage::impl::parseKVS()
{
    if (mAccessor)
    {
        uint32_t persistSize = mAccessor->size();

        if (persistSize > 0)
        {
            panda::core::Value& val = mKvs;
            char* buf = new char[persistSize + 1];

            int32_t res = mAccessor->read(buf, persistSize);

            if (res == persistSize)
            {
                buf[persistSize] = '\0';
                if (panda::core::JsonParse(buf, val))
                {
                    return true;
                }
                else
                {
                    LOGE("parse kvs data failed\n");
                }
            }
            else
            {
                LOGE("read kvs from file storage failed(req: %d, ret:%d)\n",
                    persistSize, res);
            }
        } 
    }

    return false;
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//static 
std::shared_ptr<KeyValueStorage> KeyValueStorage::OpenKeyValueStorage(const std::string& kvs)
{
    std::shared_ptr<FileStorage> fs = FileStorage::OpenFileStorage(KVS_FS_NAME);

    if (fs)
    {
        std::shared_ptr<KeyValueStorage> kvstore(new KeyValueStorage(kvs));

        kvstore->mImpl->mAccessor = fs->openFileReadWrite(kvs);

        if (kvstore->mImpl->parseKVS())
        {
            return kvstore;
        }
    }

    return nullptr;
}   


KeyValueStorage::KeyValueStorage(const std::string& kvs)
    :mImpl(new impl)
{
    /** todo something */
}

KeyValueStorage::~KeyValueStorage()
{
    /** todo something */
    mImpl->mAccessor = nullptr;
    mImpl->mFs = nullptr;
}


KeyArray KeyValueStorage::getAllKeys()
{
    return mImpl->mKvs.getMembers();
}

bool KeyValueStorage::hasKey(KeyType& key)
{
    return mImpl->mKvs.isMember(key);
}

bool KeyValueStorage::removeKey(KeyType& key)
{
    mImpl->mKvs.removeMember(key);
    return true;
}

bool KeyValueStorage::removeAllKeys()
{
    mImpl->mKvs.clear();
    return true;
}

bool KeyValueStorage::reset()
{
    /** todo something */
    return true;
}

bool KeyValueStorage::syncToStorage()
{
    std::string valStr = "";
    if (JsonWriteRaw(mImpl->mKvs, valStr))
    {
        if (mImpl->mAccessor)
        {
            if (bool(mImpl->mAccessor->seek(0)))
            {
                int32_t res = mImpl->mAccessor->write(valStr.c_str(), valStr.size() + 1);
                return (res == (valStr.size() + 1));
            }            
        }
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, std::string& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asString();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, int8_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = (int8_t)mImpl->mKvs[key].asInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, int16_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = (int16_t)mImpl->mKvs[key].asInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, int32_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, int64_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asInt64();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, uint8_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = (uint8_t)mImpl->mKvs[key].asUInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, uint16_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = (uint16_t)mImpl->mKvs[key].asUInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, uint32_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asUInt();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, uint64_t& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asUInt64();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, float& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asFloat();
        return true;
    }

    return false;
}

bool KeyValueStorage::getValue(KeyType& key, double& val)
{
    if (mImpl->mKvs.isMember(key))
    {
        val = mImpl->mKvs[key].asDouble();
        return true;
    }

    return false;
}

bool KeyValueStorage::setValue(KeyType& key, const std::string& val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, int8_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, int16_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, int32_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, int64_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, uint8_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, uint16_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, uint32_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, uint64_t val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, float val)
{
    mImpl->mKvs[key] = val;
    return true;
}

bool KeyValueStorage::setValue(KeyType& key, double val)
{
    mImpl->mKvs[key] = val;
    return true;
}

} /** namespace per */
} /** namespace panda */
